package org.openapplet.tomcat.core;

import org.openapplet.tomcat.util.Logger;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket=null;
        Socket socket=null;
        try {
            Logger.log("服务已启动，监听80端口");
            serverSocket=new ServerSocket(80);

            while(true){
                socket = serverSocket.accept();
                Logger.log("访问者IP"+socket.getInetAddress().getHostAddress());
                new Thread(new RequestThread(socket)).start();
            }


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
class RequestThread implements Runnable{

    private Socket socket;
    public RequestThread(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        InputStream inputStream= null;
        try {
            inputStream = this.socket.getInputStream();
            BufferedReader bufferedInputStream=new BufferedReader(new InputStreamReader(inputStream));
            List<String> requests=new ArrayList<String>();
            String line=bufferedInputStream.readLine();
//            if(line!=null){
//
//                System.out.println("请求地址:"+url);
//            }
            while(line!=null) {
                requests.add(line);
                line=bufferedInputStream.readLine();
            }
            if(requests.size()>0)
            {
                String url=requests.get(0).split(" ")[1];
                System.out.println(url);
                List<String> list=ReaderResource.readHTML(new File("webapps/"+url));
                for (String html:list){
                    System.out.println("html:"+html);
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}